/*
 * @Description:
 * @Version: 3.0
 * @Autor: biao.hu
 * @Date: 2021-10-18 19:52:13
 * @LastEditors: biao.hu
 * @LastEditTime: 2021-10-18 20:16:48
 */
package mcontext

import (
	"context"
	"fmt"
	"time"
)

// 通过cancel关闭
func CtxCancel() {
	ctx, cancel := context.WithCancel(context.Background())
	go func(ctx context.Context) {
		select {
		case <-ctx.Done():
			fmt.Println(ctx.Err())
		case <-time.After(time.Millisecond * 100):
			fmt.Println("Time out")
		}
	}(ctx)
	time.Sleep(1 * time.Second)
	cancel()

}

// 通过超时自动触发
func CtxTimeout() {
	ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*10)
	defer cancel()

	go func(ctx context.Context) {
		select {
		case <-ctx.Done():
			fmt.Println(ctx.Err())
		case <-time.After(time.Millisecond * 100):
			fmt.Println("time out")
		}
	}(ctx)
	time.Sleep(1 * time.Second)
}

// 通过截止时间触发time out
func CtxDeadline() {
	ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(10*time.Millisecond))
	defer cancel()
	go func(ctx context.Context) {
		select {
		case <-ctx.Done():
			fmt.Println(ctx.Err())
		case <-time.After(time.Millisecond * 100):
			fmt.Println("time out")
		}
	}(ctx)

	time.Sleep(1 * time.Second)
}

// 通过key->value传递参数
func CtxValue() {
	ctx := context.WithValue(context.Background(), "user", "hello")
	go func(ctx context.Context) {
		v, ok := ctx.Value("user").(string)
		if ok {
			fmt.Println("pass user value ", v)
		}
	}(ctx)

	time.Sleep(1 * time.Second)
}
